// Copyright (c) 2022, hzmes and contributors
// For license information, please see license.txt

frappe.ui.form.on('SRM Inquiry', {
	refresh: function(frm) {
		if (frm.is_new() && !frm.doc.due_date) {
			frm.set_value('due_date', frappe.datetime.add_days(frappe.datetime.get_today(), 7))
		}
		
		// 上拉报价单到弹窗中, 选择后可直接生成比价单:
		if ( frappe.user.has_role('SRM Purchase') && !frm.is_new()) {
			frm.add_custom_button(__('Price Comparison'), function() {
				// 必须是提交状态
				if (frm.doc.docstatus == 0 || !frm.doc.docstatus)  {
					frappe.throw("未提交的询价单不能进行比价!")
				}
				else (frm.doc.docstatus == 1)
				{
					// 判断是否已经生成过比价单
					frappe.db.get_list('SRM Price Compare',{filters:{'from_inquiry': frm.doc.name}, as_list:true})
						.then( (r) => {
							// 该询价单已经生成过比价单
							if (r[0]) {
								// frappe.set_route("Form", "SRM Price Compare", r[0][0]);
								frappe.msgprint(`已经有比价单记录,点击链接查看:<a href="http://umsrm.unionman.net:8070/app/srm-price-compare/${r[0][0]}">比价单</a>`)
							}
							else {
								// 调用JS方法
								compare_price({
									frm: frm,
									method: 'get_data_from_srm_quotation',
									args: {docname: frm.doc.name}
								})
							}
						})
				}
			})
		}
	},

	setup: function(frm) {
		// 限制供应商选择范围
		frm.set_query('supplier_number', 'supplier_subs', function(doc, cdt, cdn) {
			const rorw = locals[cdt][cdn];
			return {
				'filters': { managestatus: ['in', ['四级', '三级', '二级']] }
			}
		});
	},

});


frappe.ui.form.on('SRM Inquiry Supplier Sub', {
	// refresh: function(frm) {

	// }

	// 2023-03-21根据供应商自动携带联系人: 取联系人1中的启用状态的第一个邮箱
	supplier_number: function(frm, cdt, cdn) {
		let row = locals[cdt][cdn];
		let email_get = '';
		let full_name_get = '';
		let r = frappe.db.get_list('SRM Supplier Contact Sub',
                   {filters:{'parent': row.supplier_number, 'enable': 1}, fields:['email_address', 'full_name'], as_list:true}
			).then( (r) => {
				if (r) {
					email_get = r[0][0];
					full_name_get = r[0][1];
					// console.log(r);
				}
				else {frappe.msgprint("联系人1中没有启用状态的联系邮箱!")}
			}).then ( () => {
				// console.log(full_name_get);
				row.receive_email = email_get;
				row.receiver_name = full_name_get;
				frm.refresh_field('supplier_subs');
			})
	}
});

let compare_price = function(opts) {
	let frm = opts.frm;
	// let items_data = opts.frm.doc.items
	// 定义data变量
	let data = [];
	// 调用py方法
	frappe.call({
		method: opts.method,
		doc: frm.doc,
		args: opts.args,
		freeze: true,
		freeze_message: __("Creating..."),
		callback: function(r) {
			// data.push(r.message[0]);
			data = r.message;
			// console.log(data);
		}
	}).then(()=>{
		// 定义弹窗的子表字段(有参考价值)
		const child_fields = 
		[ 
			{fieldtype:'Read Only',fieldname:"supplier_name",read_only: 1,in_list_view: 1,label: __('Supplier Name'),columns: 2}, 
			{fieldtype:'Read Only',fieldname:"material_number",in_list_view: 1,read_only: 1,label: __('Material Number')}, 
			{fieldtype:'Read Only',fieldname:"material_name",read_only: 1,in_list_view: 1,label: __('Material Name'), columns: 2}, 
			{fieldtype:'Read Only',fieldname:"material_model",read_only: 1,in_list_view: 0,label: __('Material Model')},
			{fieldtype:'Read Only',fieldname:"price",read_only: 1,in_list_view: 1,label: __('Price'),columns: 1}, 
			{fieldtype:'Read Only',fieldname:"tax_price",read_only: 1,in_list_view: 1,label: __('Tax Price'),columns: 1}, 
			{fieldtype:'Check',fieldname:"selected",read_only: 0,in_list_view: 1,label: __('Selected'),columns: 1},
			{fieldtype:'Select',fieldname:"selected_reason",options: ["","最低价","备选"],read_only: 0,in_list_view: 1,label: __('Selected Reason'),columns: 1},
			{fieldtype:'Read Only',fieldname:"tax_rate",in_list_view: 1,label: __('Tax Rate'),columns: 1},
			{fieldtype:'Read Only',fieldname:"row_name",in_list_view: 0,label: __('Row Name'),columns: 1},
		];
	
		let resulte_data = [];
		// 定义Dialog
		const dialog = new frappe.ui.Dialog({
			title: __("比价"),
			// 大窗口
			size: 'extra-large',
			// 定义弹窗的所有字段
			fields: [
				{
					fieldtype:'Data',
					fieldname:"material_model",
					// default: opts.material_model,
					read_only: 0,
					hidden: 0,
					label: __('Material Model'),
					onchange: () => {
						var material_model = cur_dialog.fields_dict.material_model.value;
						if (material_model) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_number = cur_dialog.fields_dict.material_number.value;
							var material_name = cur_dialog.fields_dict.material_name.value;
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_model && material_name) {
								resulte_data = data.filter(ele => ele.material_model.includes(material_model) && ele.material_name.includes(material_name))
							}
							else if (material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_model) {
								resulte_data = data.filter(ele => ele.material_model.includes(material_model))
							}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!material_model) {
							cur_dialog.fields_dict.delivery_items.df.data = data
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Column Break"},
				{
					fieldtype:'Data',
					fieldname:"material_name",
					// default: opts.assign_qty,
					read_only: 0,
					label: __('Material Name'),
					onchange: () => {
						var material_name = cur_dialog.fields_dict.material_name.value;
						if (material_name) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_number = cur_dialog.fields_dict.material_number.value;
							var material_model = cur_dialog.fields_dict.material_model.value;
							// let resulte_data = [];
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_number && material_name) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name))
							}
							else if (material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_name) {
								resulte_data = data.filter(ele => ele.material_name.includes(material_name))
							}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!material_name) {
							cur_dialog.fields_dict.delivery_items.df.data = data
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Column Break"},
				{
					fieldtype:'Data',
					fieldname:"material_number",
					// default: opts.need_date,
					read_only: 0,
					label: __('Material Number'),
					onchange: () => {
						var material_number = cur_dialog.fields_dict.material_number.value;
						if (material_number) {
							// cur_dialog.fields_dict.delivery_items.df.data = [];
							var material_name = cur_dialog.fields_dict.material_name.value;
							var material_model = cur_dialog.fields_dict.material_model.value;
							// let resulte_data = [];
							if (material_number && material_name && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name) && ele.material_model.includes(material_model))
							}
							else if (material_number && material_name) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_name.includes(material_name))
							}
							else if (material_number && material_model) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number) && ele.material_model.includes(material_model))
							}
							else if (material_number) {
								resulte_data = data.filter(ele => ele.material_number.includes(material_number))
							}
							console.log(resulte_data);
							cur_dialog.fields_dict.delivery_items.df.data = resulte_data;
						}
						else if (!material_number) {
							cur_dialog.fields_dict.delivery_items.df.data = data;
						}
						cur_dialog.fields_dict.delivery_items.grid.refresh();
					}
				},
				{fieldtype: "Section Break"},
				// 定义弹窗中的表字段(很有参考价值)
				{
					fieldname: "delivery_items",
					// 通过fieldtype定义
					fieldtype: "Table",
					label: "Items",
					checkboxColumn: false,
					cannot_add_rows: 1,
					in_place_edit: true,
					read_only: 1,
					reqd: 1,
					data: data,
					fields: child_fields
				},
			],
			
			primary_action: function() {
				// 变量定义
				let items_selected = [];
				// 获取窗口中的子表明细
				// items_selected = cur_dialog.fields_dict.delivery_items.grid.get_selected_children()
				// 2023-04-03: 默认是全部行记录都要写入比价单,不管是否选中
				items_selected = cur_dialog.fields_dict.delivery_items.grid.data;
				if (items_selected.length > 0 ){
					console.log(items_selected);
					// 纯JS的New Doc
					let new_doc = frappe.model.get_new_doc("SRM Price Compare");
					new_doc.date = frappe.datetime.get_today();
					new_doc.price_type = "物料比价";
					new_doc.to_erp_price = 1;
					new_doc.from_inquiry = frm.doc.name;
					new_doc.currency = frm.doc.currency;
					// 纯JS的New Child Doc
					for (let d of items_selected){
						let new_doc_sub = frappe.model.add_child(new_doc, "SRM Price Compare Quotation Sub", "material_subs");
						new_doc_sub.supplier_number = d.supplier_number;
						new_doc_sub.supplier_name = d.supplier_name;
						new_doc_sub.material_number = d.material_number;
						new_doc_sub.material_name = d.material_name;
						new_doc_sub.material_model = d.material_model;
						new_doc_sub.price = d.price;
						new_doc_sub.tax_rate = d.tax_rate;
						new_doc_sub.tax_price = d.tax_price;
						new_doc_sub.moq = d.moq;
						new_doc_sub.mpq = d.mpq;
						new_doc_sub.lead_time = d.lead_time;
						new_doc_sub.selected = d.selected;
						new_doc_sub.selected_reason = d.selected_reason;
						new_doc_sub.from_inquiry_material_sub = d.row_name;
					}
					frappe.set_route("Form", new_doc.doctype, new_doc.name);
				}
				else {frappe.msgprint("没有符合条件的行记录!")}
				// items_selected.forEach(item => {frm.add_child('items',item);});
				// frm.refresh_field("items");
				
				this.hide();
			},
			primary_action_label: __('Create SRM Price Compare')
		});


	dialog.show();
	})
	
}